import React, { useState, useEffect } from 'react';
import Select from 'react-select';
import { useNavigate } from 'react-router-dom';

function DynamicTablePage() {
    const [tableNames, setTableNames] = useState([]);
    const [keyword, setKeyword] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const [selectedTable, setSelectedTable] = useState(null);
    const navigate = useNavigate();

    const fetchTableNames = async (inputValue = '') => {
        setIsLoading(true);
        try {
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/allTableName?keyword=${inputValue}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            const validTableNames = Array.isArray(data.data) ? data.data.map((name) => ({ value: name, label: name })) : [];
            setTableNames(validTableNames);
        } catch (error) {
            console.error('Error fetching table names:', error);
        } finally {
            setIsLoading(false);
        }
    };

    const handleInputChange = (newValue) => {
        const inputValue = newValue.replace(/\W/g, '');
        setKeyword(inputValue);
        fetchTableNames(inputValue);
    };

    const handleSelectChange = (selectedOption) => {
        setSelectedTable(selectedOption);
    };

    const handleExport = async () => {
        if (!selectedTable) return;

        try {
            const tableName = selectedTable.value;
            const response = await fetch(`http://127.0.0.1:9991/api/admin/demo/getAllColumns?tableName=${tableName}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                },
            });

            if (response.ok) {
                const data = await response.json();
                // 跳转到 custom 页面，同时传递数据和选中的表名
                navigate('/custom', {
                    state: {
                        data: data.data,
                        selectedTableName: tableName
                    }
                });
            } else {
                console.error('导出失败', response.statusText);
            }
        } catch (error) {
            console.error('请求失败', error);
        }
    };

    const handleConfigure = () => {
        if (!selectedTable) return;

        // 跳转到配置页面，并传递选中的表名
        navigate('/config', {
            state: {
                selectedTableName: selectedTable.value
            }
        });
    };

    useEffect(() => {
        fetchTableNames();
    }, []);

    const customStyles = {
        control: (provided) => ({
            ...provided,
            width: 300,
            height: 50,
            minHeight: 50
        })
    };

    return (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', paddingTop: '50px' }}>
            <h1>动态页面展示</h1>
            <Select
                isLoading={isLoading}
                options={tableNames}
                onInputChange={handleInputChange}
                onChange={handleSelectChange}
                placeholder="输入筛选关键词"
                styles={customStyles}
            />
            <button
                style={{ marginTop: '20px' }}
                onClick={handleExport}
                disabled={!selectedTable}
            >
                导出
            </button>
            <button
                style={{ marginTop: '20px' }}
                onClick={handleConfigure}
                disabled={!selectedTable}
            >
                配置
            </button>
        </div>
    );
}

export default DynamicTablePage;